package cn.yuanqiao.archive.management.utils;

import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.*;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.management.mapper.PackMapper;
import cn.yuanqiao.archive.management.utils.entity.*;
import cn.yuanqiao.archive.storeRoom.util.DateUtil;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantItemFolderMapper;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantYqdaFolderMapper;
import cn.yuanqiao.common.core.context.ResponseUtils;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.spring.SpringUtils;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 元数据Util
 * @author gaolh
 *
 */

public class PackUtil {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private ITenantSysConfigService sysConfigService;

	@Autowired
	private PackMapper packMapper;

	@Autowired
	private TenantYqItemMapper itemMapper;

	@Autowired
	private TenantYqFolderMapper folderMapper;

	@Autowired
	private TenantYqdaMapper yqdaMapper;

	@Autowired
	private TenantCategoryMapper categoryMapper;

	@Autowired
	private TenantItemFolderMapper itemFolderMapper;

	@Autowired
	private TenantMdataListMapper mdataListMapper;

	@Autowired
	private TenantYqdaFolderMapper yqdaFolderMapper;

	@Autowired
	private TenantCodeListMapper codeListMapper;

	@Autowired
	private TenantYqdaDocumentMapper documentMapper;

	private Map<String,Map<String,String>> dicts = getAllDictNameToMap();

	public static String userCode;

	/**
	 * 组包
	 * @param ids 档案Id
	 * @param typeId 门类Id
	 * @throws Exception
	 */
	public String getPersistenPackage(String ids,Long typeId,String nestedPath) throws Exception {
		userCode = SecurityUtils.getTenantCode();
//		userCode = "BJYQ";
		String categoryTable = userCode + "_CATEGORY";
        //查询门类分表
		List<Map<String,Object>> types = SpringUtils.getBean(PackMapper.class).selectCategory(categoryTable,Long.valueOf(typeId));
		String type = types.get(0).get("TYPE").toString();
		String zip = null;
		Map<String, Object> dataMap = null;
		Map<String, Object> archiveDetailMap = null;
		if ("0".equals(type)){
			dataMap= getFilePersistenPackage(ids, typeId, nestedPath, "元数据信息.xml");
			PersistentFilePackage filePersistenPackage =(PersistentFilePackage) dataMap.get("persistentFilePackage");
			zip = createFileZip(filePersistenPackage,nestedPath);
			archiveDetailMap = (Map<String, Object>) dataMap.get("archiveDetail");
			archiveDetailMap.put("CATEGORY_TYPE","f");
			archiveDetailMap.put("CATEGORY_ID",typeId);
		}else {
			dataMap = getFolderPersistenPackage(ids, typeId, nestedPath);
			PersistentFolderPackage folderPersistenPackage = (PersistentFolderPackage) dataMap.get("persistentFolderPackage");
			zip = createFolderZip(folderPersistenPackage,nestedPath);
			archiveDetailMap = (Map<String, Object>) dataMap.get("archiveDetail");
			archiveDetailMap.put("CATEGORY_TYPE","v");
			archiveDetailMap.put("CATEGORY_ID",typeId);
		}
		return zip;
	}

	public String createFileZip(PersistentFilePackage persistentFilePackage,String nestedPath) throws IOException {
		// 获取文件夹路径
		String packagePath=nestedPath;
		String folder = packagePath +"\\"+ persistentFilePackage.getFileName();
		// 建立存放Zip文件的路径
		File zipFile = new File(folder + ".zip");
		if (!zipFile.getParentFile().exists()) {
			zipFile.getParentFile().mkdirs();
		}
		// 新建ZipOutputStream输出流
		ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));

		// 添加XML文件至Zip压缩包
		ZipEntry zipEntryXML = new ZipEntry(persistentFilePackage.getXMLName());
		zipOut.putNextEntry(zipEntryXML);
		zipOut.write(persistentFilePackage.getXMLContent().getBytes());
		zipOut.closeEntry();

		Asip asip = new Asip();
		//信息包唯一标识,后期如有信息包表可用来存储
		asip.setM1(persistentFilePackage.getFileName());
		asip.setM2(SpringUtils.getBean(ITenantSysConfigService.class).selectConfigByKey("HD_DA_PACKAGE_TYPE"));
		asip.setM3("");
		asip.setM4(DateUtil.getDateString());
		asip.setM5("");
		asip.setM6(folder);
		asip.setM7("无");

		String mntPath = SpringUtils.getBean(ITenantSysConfigService.class).selectConfigByKey("YQ_MNT");

		XStream xStream = new XStream(new DomDriver());
		xStream.processAnnotations(Asip.class);
		//OutputStream os = new FileOutputStream(packagePath+"/"+"说明文件.xml");
		ZipEntry zipEntryXMLFile = new ZipEntry("说明文件.xml");
		zipOut.putNextEntry(zipEntryXMLFile);
		zipOut.write(xStream.toXML(asip).getBytes());
		zipOut.closeEntry();

		// 添加File文件夹中的文件至Zip压缩包
		List<File> files = persistentFilePackage.getFiles();
		if (files != null && files.size() > 0) {
			for (File file : files) {
				ZipEntry zipEntryFile = new ZipEntry("File/" + file.getName());
				zipOut.putNextEntry(zipEntryFile);
				FileInputStream fis = new FileInputStream(mntPath+file.getPath());
				byte[] buffer = new byte[1024];
				int len;
				while ((len = fis.read(buffer)) > 0) {
					zipOut.write(buffer, 0, len);
				}
				zipOut.closeEntry();
				fis.close();
			}
		}

		// 关闭流
		zipOut.close();

		// 返回ZIP包路径
		return zipFile.getAbsolutePath();
	}

	public void zipFolder(String sourceFolderPath, String zipFilePath) throws IOException {
		Path sourcePath = Paths.get(sourceFolderPath);
		try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFilePath))) {
			Files.walk(sourcePath)
					.filter(path -> !Files.isDirectory(path))
					.forEach(path -> {
						ZipEntry zipEntry = new ZipEntry(sourcePath.relativize(path).toString());
						try {
							zipOutputStream.putNextEntry(zipEntry);
							Files.copy(path, zipOutputStream);
							zipOutputStream.closeEntry();
						} catch (IOException e) {
							e.printStackTrace();
						}
					});
		}
	}

	public static void deleteFolder(File folder) {
		if (folder.isDirectory()) {
			File[] files = folder.listFiles();
			if (files != null) {
				for (File file : files) {
					deleteFolder(file);
				}
			}
		}
		folder.delete();
	}

	/*
	* 移动文件
	*
	* */
	public boolean moveFileToPath(String newFile,String newPath){
		boolean flag = false;
		File startFile=new File(newFile);
		File endDirection=new File(newPath);
		if(!endDirection.exists()) {
			endDirection.mkdirs();
		}
		File endFile=new File(endDirection+ File.separator+ startFile.getName());
		try {
			if (startFile.renameTo(endFile)) {
				System.out.println("文件移动成功！目标路径：{"+endFile.getAbsolutePath()+"}");
				flag = true;
			} else {
				System.out.println("文件移动失败！起始路径：{"+startFile.getAbsolutePath()+"}");
			}
		}catch(Exception e) {
			System.out.println("文件移动出现异常！起始路径：{"+startFile.getAbsolutePath()+"}");
		}
		return flag;
	}

	/*
	 * 下载文件
	 *
	 * */
	public void fileDownload(final HttpServletResponse response, String filePath, String fileName) throws Exception {
		byte[] bytes = FileUtil.toByteArray(filePath);
		fileName = URLEncoder.encode(fileName, "UTF-8");
		response.reset();
		ResponseUtils.defaultResponse(response);
		response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
		response.addHeader("Content-Length", "" + bytes.length);
		response.setContentType("application/octet-stream;charset=UTF-8");
		OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
		outputStream.write(bytes);
		outputStream.flush();
		outputStream.close();
		response.flushBuffer();
	}

	/*
	 * 下载文件到指定路径
	 *
	 * */
//	public void fileDownload(final HttpServletResponse response, String filePath, String fileName, String targetPath) throws Exception {
//		byte[] bytes = FileUtil.toByteArray(filePath);
//		fileName = URLEncoder.encode(fileName, "UTF-8");
//		response.reset();
//		response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
//		response.addHeader("Content-Length", "" + bytes.length);
//		response.setContentType("application/octet-stream;charset=UTF-8");
//		OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
//		String targetFilePath = targetPath + File.separator + fileName;
//			try (FileOutputStream targetStream = new FileOutputStream(targetFilePath)) {
//				targetStream.write(bytes);
//			}
//		outputStream.write(bytes);
//		outputStream.flush();
//		outputStream.close();
//		response.flushBuffer();
//	}

	/*
	 * 拷贝zip到文件夹
	 *
	 * */
	public static void copyZipFileToFolder(String zipFilePath, String targetFolderPath) throws IOException {
		File targetFolder = new File(targetFolderPath);
		if (!targetFolder.exists()) {
			targetFolder.mkdirs();
		}

		Path source = Paths.get(zipFilePath);
		Path destination = Paths.get(targetFolderPath, source.getFileName().toString());

		Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);

	}

	/**
	 * 将PersistentFolderPackage到处为zip包
	 *
	 * @param persistentFolderPackage 要生成zip包的PersistentFolderPackage对象
	 * @return 返回生成zip包的路径
	 * @throws IOException IO异常
	 */
	public String createFolderZip(PersistentFolderPackage persistentFolderPackage, String nestedPath) throws IOException {
		// 获取文件夹路径
		String packagePath=nestedPath;
		String folder = packagePath + "\\" + persistentFolderPackage.getFileName();

		// 建立存放Zip文件的路径
		File zipFile = new File(folder + ".zip");
		if (!zipFile.getParentFile().exists()) {
			zipFile.getParentFile().mkdirs();
		}

		// 新建ZipOutputStream输出流
		ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));

		// 添加XML文件至Zip压缩包
		ZipEntry zipEntryXML = new ZipEntry(persistentFolderPackage.getXMLName());
		zipOut.putNextEntry(zipEntryXML);
		zipOut.write(persistentFolderPackage.getXMLContent().getBytes());
		zipOut.closeEntry();

		Asip asip = new Asip();
		//信息包唯一标识,后期如有信息包表可用来存储
		asip.setM1(persistentFolderPackage.getFileName());
		asip.setM2(SpringUtils.getBean(ITenantSysConfigService.class).selectConfigByKey("YQ_DA_PACKAGE_TYPE"));
		asip.setM3("");
		asip.setM4(DateUtil.getDateString());
		asip.setM5("");
		asip.setM6(folder);
		asip.setM7("无");

		String mntPath = SpringUtils.getBean(ITenantSysConfigService.class).selectConfigByKey("YQ_MNT");

		XStream xStream = new XStream(new DomDriver());
		xStream.processAnnotations(Asip.class);
		ZipEntry zipEntryXML1 = new ZipEntry("说明文件.xml");
		zipOut.putNextEntry(zipEntryXML1);
		zipOut.write(xStream.toXML(asip).getBytes());
		zipOut.closeEntry();

		// 添加InnerFiles中的子文件夹及文件至Zip压缩包
		List<PersistentFilePackage> innerFiles = persistentFolderPackage.getInnerFiles();
		if (innerFiles != null && innerFiles.size() > 0) {
			for (PersistentFilePackage innerFile : innerFiles) {
				ZipEntry zipEntryFolder = new ZipEntry(innerFile.getFileName() + "/");
				zipOut.putNextEntry(zipEntryFolder);

				// 添加XML文件至子文件夹中
				ZipEntry zipEntryXMLFile = new ZipEntry(innerFile.getFileName() + "/" +innerFile.getXMLName());
				zipOut.putNextEntry(zipEntryXMLFile);
				zipOut.write(innerFile.getXMLContent().getBytes());
				zipOut.closeEntry();

				// 添加子文件夹中的文件
				List<File> files = innerFile.getFiles();
				if (files != null && files.size() > 0) {
					for (File file : files) {
						String filePath = file.getAbsolutePath();
						ZipEntry zipEntryFile = new ZipEntry(innerFile.getFileName() + "/" + "File/" + file.getName());
						zipOut.putNextEntry(zipEntryFile);
						FileInputStream fis = new FileInputStream(mntPath+file.getPath());
						byte[] buffer = new byte[1024];
						int len;
						while ((len = fis.read(buffer)) > 0) {
							zipOut.write(buffer, 0, len);
						}
						zipOut.closeEntry();
						fis.close();
					}
				}
			}
		}

		// 关闭流
		zipOut.close();
		// 返回ZIP包路径
		return zipFile.getAbsolutePath();
	}

	public static String convertStringToXML(String xmlString) throws Exception {
//		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//		DocumentBuilder builder = factory.newDocumentBuilder();
//		InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
//		org.w3c.dom.Document document = builder.parse(inputStream);
//		TransformerFactory tf = TransformerFactory.newInstance();
//		Transformer transformer = tf.newTransformer();
//		transformer.setOutputProperty("indent", "yes"); // 设置输出格式化
//		StringWriter sw = new StringWriter();
//		transformer.transform(new DOMSource(document), new StreamResult(sw));
//		return sw.toString();

//		try {
//			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//			DocumentBuilder builder = factory.newDocumentBuilder();
//			Document document = builder.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8")));
//
//			TransformerFactory tf = TransformerFactory.newInstance();
//			Transformer transformer = tf.newTransformer();
//			transformer.setOutputProperty("indent", "yes"); // 设置输出格式化
//
//			StringWriter sw = new StringWriter();
//			transformer.transform(new DOMSource(document), new StreamResult(sw));
//
//			return sw.toString();
//		} catch (Exception e) {
//			e.printStackTrace(); // 打印异常信息
//			return null; // 或者返回一个特定的错误标识
//		}

		return xmlString;
	}

	//id只能是单个id，一个档案一个包
	public Map<String,Object> getFolderPersistenPackage(String ids, Long typeId, String place) throws Exception {
		Map<String,Object> resultMap = new HashMap<>();
		String path = "";
		PersistentFolderPackage persistentFolderPackage = new PersistentFolderPackage();
		persistentFolderPackage.setXMLName("案卷元数据.xml");
		try {
			String categoryTable = userCode + "_CATEGORY";
            //（门类表）
			List<Map<String,Object>> types = SpringUtils.getBean(PackMapper.class).selectCategory(categoryTable,Long.valueOf(typeId));
			//查询表名
			String type = types.get(0).get("TYPE").toString();
			//
//			String tableName = "1".equals(type)?types.get(0).get("FOLDER_TABLE_NAME").toString():types.get(0).get("FILE_TABLE_NAME").toString();
			String tableName = "0".equals(type)?types.get(0).get("FILE_TABLE_NAME").toString():types.get(0).get("FOLDER_TABLE_NAME").toString();
			String mdataTable = userCode + "_MDATA_LIST";

			//方案Id
			String groupId = types.get(0).get("GROUP_ID").toString();
			String metaDatas = "";

			//查询需要使用的元数据信息 加上 type=1  查卷层
			List<Map<String,Object>> MdataList = SpringUtils.getBean(PackMapper.class).selectMdata(mdataTable,Long.valueOf(groupId),1);
			HashMap<String,Object> lenMap = new HashMap<String, Object>();
			List<String> CATALOGUES = new ArrayList<String>();
			List<Map<String,Object>> mDataList = new ArrayList<Map<String,Object>>();
			List<Map<String,Object>> fileMDataList = new ArrayList<Map<String,Object>>();

            //（档号规则明细表）
			String vfeType = types.get(0).get("TYPE").toString();
			if (vfeType.equals("0")) {
				vfeType = "e";
			} else if (vfeType.equals("1")) {
				vfeType = "f";
			} else {
				vfeType = "v";
			}
			String codeListTable = userCode + "_CODELIST";
			String codeRuleTable = userCode + "_CODERULE";
			List<Map<String,Object>> dhs = SpringUtils.getBean(PackMapper.class).selectCodeList(codeListTable,codeRuleTable,vfeType,Long.valueOf(typeId));
			for(Map<String,Object> m : dhs) {
				String node_val = m.get("NODE_VALUE").toString();
				CATALOGUES.add(node_val);
				lenMap.put(node_val, m.get("LEN"));
			}
			CATALOGUES.add("DH");
			for (Map<String,Object> item : MdataList){
				if ("3".equals(item.get("MD_LEVEL"))){
					fileMDataList.add(item);
				}else {
					mDataList.add(item);
				}
			}
			if(!StringUtils.isNULL(metaDatas)) {
				metaDatas = metaDatas.substring(0,metaDatas.length()-1);
			}
			//查询档案信息
			List<Map<String,Object>> daList ;

			//（档案表）
			daList = SpringUtils.getBean(PackMapper.class).selectDa(tableName,ids);

			List<ArchivingPackage> packages = new ArrayList<ArchivingPackage>();

			for(Map<String,Object> da : daList) {
				resultMap.put("archiveDetail",da);

				String xml = getMetaDataXml(mDataList, groupId, da,"1");
				List<String> cataLoguesVal = new ArrayList<String>();

				for(String catalogue : CATALOGUES) {
					if(da.containsKey(catalogue)) {
						//判断位数 是否需要补零 syd
						String len = (String)lenMap.get(catalogue);
						String col = "";
						if(!StringUtils.isNULL(da.get(catalogue))){
							col = da.get(catalogue).toString();
						}
						if(!"0".equals(len) && null!=len && !"null".equals(len)) {
							int l = Integer.valueOf(len);
							int m = Integer.valueOf(col.length());
							if(m<l) {
								String v = "";
								int more = l-m;
								for(int i=0;i<more;i++) {
									v+="0";
								}
								v = v+col;
								cataLoguesVal.add(v);
							}else {
								cataLoguesVal.add(col);
							}
						}else {
							cataLoguesVal.add(col);
						}
					}
				}

				FilePackage filePackage = getFileXml(fileMDataList, typeId, da);
				String logXml = getLogs(mDataList, groupId, da,"v");
				xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ArchiveMetadata><聚合层次>案卷</聚合层次>"+xml+logXml+filePackage.getFileXml()+"</ArchiveMetadata>";
//				persistentFolderPackage.setXMLContent(convertStringToXML(xml));
				//
				persistentFolderPackage.setXMLContent(packXml(Long.valueOf(ids),Integer.valueOf(type),typeId,1));
				persistentFolderPackage.setFileName(da.get("DH").toString());
                //（卷与件关联关系表）
				String folder = userCode + "_YQDA_FOLDER";
				List<Map<String, Object>> listResult = SpringUtils.getBean(PackMapper.class).selectFolder(folder,ids);

				List<PersistentFilePackage> innerFiles = new ArrayList<>();
				for (Map<String, Object> item :listResult) {
					PersistentFilePackage innerFile = (PersistentFilePackage)getFilePersistenPackage(item.get("DA_ID").toString(), typeId, place, "卷内件元数据.xml").get("persistentFilePackage");
					innerFiles.add(innerFile);
				}
				persistentFolderPackage.setInnerFiles(innerFiles);
			}
			//path = setPackagePath(packages,place);
		}catch (ServiceException e){
			e.printStackTrace();
			throw e;
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println(111);
		resultMap.put("persistentFolderPackage",persistentFolderPackage);
		return resultMap;
	}

	//id只能是单个id，一个档案一个包
	public Map<String,Object> getFilePersistenPackage(String ids,Long typeId,String place,String xmlName) throws Exception {
		Map<String,Object> resultMap = new HashMap<>();
		PersistentFilePackage persistentFilePackage = new PersistentFilePackage();
		persistentFilePackage.setXMLName(xmlName);
		String path = "";
		try {
			String categoryTable = userCode + "_CATEGORY";
            //查询门类分表
			List<Map<String,Object>> types = SpringUtils.getBean(PackMapper.class).selectCategory(categoryTable,Long.valueOf(typeId));
			//查询表名
			String type = types.get(0).get("TYPE").toString();
			//
			String tableName = types.get(0).get("FILE_TABLE_NAME").toString();
			String EFILE_TABLE_NAME = types.get(0).get("EFILE_TABLE_NAME").toString();
			String mdataTable = userCode + "_MDATA_LIST";
			//元数据方案Id
			String groupId = types.get(0).get("GROUP_ID").toString();
			String metaDatas = "";

			//查询需要使用的元数据信息 加上 type=0  查文件层
			List<Map<String,Object>> MdataList = SpringUtils.getBean(PackMapper.class).selectMdata(mdataTable,Long.valueOf(groupId),0);

			HashMap<String,Object> lenMap = new HashMap<String, Object>();

			List<String> CATALOGUES = new ArrayList<String>();
			List<Map<String,Object>> mDataList = new ArrayList<Map<String,Object>>();
			List<Map<String,Object>> fileMDataList = new ArrayList<Map<String,Object>>();

			//档号规则模板表，档号规则明细表
			String vfeType = types.get(0).get("TYPE").toString();
			if (vfeType.equals("0")) {
				vfeType = "f";
			} else if (vfeType.equals("1")) {
				vfeType = "v";
			} else {
				vfeType = "i";
			}
			String codeListTable = userCode + "_CODELIST";
			String codeRuleTable = userCode + "_CODERULE";
			List<Map<String,Object>> dhs = SpringUtils.getBean(PackMapper.class).selectCodeList(codeListTable,codeRuleTable,vfeType,Long.valueOf(typeId));
			for(Map<String,Object> m : dhs) {
				String node_val = m.get("NODE_VALUE").toString();
				CATALOGUES.add(node_val);
				lenMap.put(node_val, m.get("LEN"));
			}
			CATALOGUES.add("DH");
			for (Map<String,Object> item : MdataList){
				if ("3".equals(item.get("MD_LEVEL"))){
					fileMDataList.add(item);
				}else {
					mDataList.add(item);
				}
			}
			if(!StringUtils.isNULL(metaDatas)) {
				metaDatas = metaDatas.substring(0,metaDatas.length()-1);
			}

			//查询档案信息
			List<Map<String,Object>> daList = SpringUtils.getBean(PackMapper.class).selectDa(tableName,ids);

			List<ArchivingPackage> packages = new ArrayList<ArchivingPackage>();

			Map<String,Map<String,String>> dicts = getAllDictNameToMap();
			for(Map<String,Object> da : daList) {
				resultMap.put("archiveDetail",da);

				String xml = getMetaDataXml(mDataList, groupId, da,"0");
				List<String> cataLoguesVal = new ArrayList<String>();

				for(String catalogue : CATALOGUES) {
					if(da.containsKey(catalogue)&&lenMap.containsKey(catalogue)) {
						//判断位数 是否需要补零 syd
						if(da.get(catalogue)!=null){
							String len = lenMap.get(catalogue).toString();
							String col = da.get(catalogue).toString();
							if(!"0".equals(len) && null!=len && !"null".equals(len)) {
								int l = Integer.valueOf(len);
								int m = Integer.valueOf(col.length());
								if(m<l) {
									String v = "";
									int more = l-m;
									for(int i=0;i<more;i++) {
										v+="0";
									}
									v = v+col;
									cataLoguesVal.add(v);
								}else {
									cataLoguesVal.add(col);
								}
							}else {
								cataLoguesVal.add(col);
							}
						}
					}
				}

				FilePackage filePackage = getFileXml(fileMDataList, typeId, da);
				String logXml = getLogs(mDataList, groupId, da,"f");
				StringBuilder xmlDocument = new StringBuilder("<组件集合>");

                //（电子文件表）
				List<Map<String, Object>> listDocument = SpringUtils.getBean(PackMapper.class).selectEfile(EFILE_TABLE_NAME,ids);

				for (Map<String, Object> item: listDocument){
					xmlDocument.append("<组件>");
					xmlDocument.append("<格式信息>").append(item.get("DOC_FILE_TYPE")).append("</格式信息>");
					xmlDocument.append("<计算机文件名>").append(item.get("DOC_NAME")).append("</计算机文件名>");
					xmlDocument.append("<计算机文件大小>").append(item.get("DOC_FILE_SIZE")).append("</计算机文件大小>");
					xmlDocument.append("<文档创建程序>").append(item.get("DOC_SYSTEM")).append("</文档创建程序>");
					xmlDocument.append("<文件名称>").append(item.get("REAL_DOC_NAME")).append("</文件名称>");
					String m245 = "";
					switch (item.get("TYPE").toString()) {
						case "1":
							m245 = "正文";
							break;
						case "2":
							m245 = "文稿";
							break;
						case "3":
							m245 = "批报件";
							break;
						case "4":
							m245 = "附件";
							break;
						default:
							m245 = "";
							break;
					}
					xmlDocument.append("<文件类型>").append(m245).append("</文件类型>");
					if ("正文".equals(m245)){
//						xmlDocument.append("<M103>").append(getFileChecksum(new File(SystemConfig.getParamValueByCode("HD_MNT")+item.get("PATH").toString()))).append("</M103>");
						xmlDocument.append("<M103>").append(getFileChecksum(new File(SpringUtils.getBean(ITenantSysConfigService.class).selectConfigByKey("YQ_MNT")+item.get("PATH").toString()))).append("</M103>");
//						xmlDocument.append("<M103>").append(getFileChecksum(new File(sysConfigService.selectConfigByKey("YQ_MNT")+item.get("PATH").toString()))).append("</M103>");
					}
					xmlDocument.append("</组件>");
				}
				xmlDocument.append("</组件集合>");

				xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ArchiveMetadata><聚合层次>文件</聚合层次>"+xml+logXml+filePackage.getFileXml()+xmlDocument.toString()+"</ArchiveMetadata>";

//				persistentFilePackage.setXMLContent(convertStringToXML(xml));
				//
				persistentFilePackage.setXMLContent(packXml(Long.valueOf(ids),Integer.valueOf(type),typeId,0));

//				//测试
//				da.put("DH","000000");
				if(da!= null && (da.get("DH") == null || "".equals(da.get("DH").toString()))){
					throw new ServiceException("档号没有值,打包失败！");
				}
				persistentFilePackage.setFileName(da.get("DH").toString());

				List<File> files = new ArrayList<>();
				for (Map<String, Object> item: listDocument){
					files.add(new File(item.get("PATH").toString()));
				}

				persistentFilePackage.setFiles(files);
			}

			//path = setPackagePath(packages,place);

		}catch (ServiceException e){
			logger.error(e.getMessage(),e);
			throw e;
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		resultMap.put("persistentFilePackage",persistentFilePackage);
		return resultMap;
	}

	public static String getFileChecksum(File file) {
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			FileInputStream inputStream = new FileInputStream(file);
			byte[] buffer = new byte[8192];
			int read = 0;
			while ((read = inputStream.read(buffer)) != -1) {
				digest.update(buffer, 0, read);
			}
			byte[] md5sum = digest.digest();
			StringBuilder stringBuilder = new StringBuilder();
			for (byte b : md5sum) {
				stringBuilder.append(String.format("%02x", b & 0xff));
			}
			return stringBuilder.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public Map<String,Map<String,String>> getAllDictNameToMap() {
		Connection conn = null;
		Statement stat = null;
		ResultSet rs = null;
		Map<String,Map<String,String>> result = new HashMap<String, Map<String,String>>();
		try {
            //（字典类型表）
			userCode = SecurityUtils.getTenantCode();
			String dictTypeTable = userCode + "_DICT_TYPE";
			String dictDataTable = userCode + "_DICT_DATA";
			String status = "0";
			List<Map<String,Object>> dictList = SpringUtils.getBean(PackMapper.class).selectDictType(dictTypeTable,status);

			for(Map<String,Object> dict : dictList) {
				List<Map<String,Object>> data = SpringUtils.getBean(PackMapper.class).selectDictData(dictDataTable,dict.get("DICT_TYPE").toString(),status);
				Map<String,String> dictVal = new HashMap<String, String>();
				for (Map<String, Object> map : data) {
					dictVal.put(map.get("DICT_VALUE").toString(),map.get("DICT_LABEL").toString());
				}
				result.put(dict.get("DICT_TYPE").toString(), dictVal);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 硬核组装,替代Json组装方式
	 * @param mDataList 元数据
	 * @param groupId 元数据方案ID
	 * @param da 档案
	 * @return
	 * @throws SQLException
	 */
	public String getMetaDataXml(List<Map<String,Object>> mDataList,String groupId,Map<String,Object> da,String type) throws SQLException {
		StringBuffer re = new StringBuffer();
		//组装基本元数据
		for(Map<String,Object> mds : mDataList) {
			if (mds.get("ELEMENT_TYPE") == null) {
				String FIELDNAME = mds.get("FIELD_NAME").toString();
				if(da.containsKey(FIELDNAME)) {
					if (!StringUtils.isNULL(da.get(FIELDNAME))){
						String value = da.get(FIELDNAME).toString();
						if(StringUtils.isNULL(value)) {
							value = mds.get("DEFAULT_VALUE").toString();
						}
						String SHOWTYPE = mds.get("SHOWTYPE").toString();
						if("5".equals(SHOWTYPE)) {
							if (!StringUtils.isNULL(dicts.get(FIELDNAME))&&!StringUtils.isNULL(dicts.get(FIELDNAME).get(value))){
								value = dicts.get(FIELDNAME).get(value);
							}
						}
						String title = mds.get("FIELD_CAPTION").toString();
						//当标题（title）没有值时跳过
						if(StringUtils.isNULL(title))continue;
						re.append("<").append(title).append(">").append(value).append("</").append(title).append(">");
					}
				}
			} else {
				String ELEMENT_TYPE = mds.get("ELEMENT_TYPE").toString();
				if("0".equals(ELEMENT_TYPE)) {
					String FIELDNAME = mds.get("FIELD_NAME").toString();
					if(da.containsKey(FIELDNAME)) {
						String value = da.get(FIELDNAME).toString();
						if(StringUtils.isNULL(value)) {
							value = mds.get("DEFAULT_VALUE").toString();
						}
						String SHOWTYPE = mds.get("SHOWTYPE").toString();
						if("5".equals(SHOWTYPE)) {
							value = dicts.get(FIELDNAME).get(value);
						}
						String title = mds.get("FIELD_CAPTION").toString();
						//当标题（title）没有值时跳过
						if(StringUtils.isNULL(title))continue;
						re.append("<").append(title).append(">").append(value).append("</").append(title).append(">");
					}
				}else {
					String element = mds.get("ZIBIANHAO").toString();
					List<Map<String,Object>> subMDataList = new ArrayList<>();
					if (!"".equals(element)){
						String mdataTable = userCode + "_MDATA_LIST";
						subMDataList= SpringUtils.getBean(PackMapper.class).selectMdataSub(mdataTable,Long.valueOf(groupId),element,0);
					}
					String xml = getMetaDataXml(subMDataList,groupId,da,type);
					String title = mds.get("FIELD_CAPTION").toString();
					//当标题（title）没有值时跳过
					if(StringUtils.isNULL(title))continue;
					re.append("<").append(title).append(">")
					.append(xml).append("</").append(title).append(">");
				}
			}

		}
		return re.toString();
	}

	/**
	 * 获取档案操作日志Xml
	 * @param mDataList 元数据明细
	 * @param groupId 门类ID
	 * @param da 档案
	 * @return
	 * @throws SQLException
	 */
	public String getLogs(List<Map<String,Object>> mDataList,String groupId,Map<String,Object> da,String type) throws SQLException {
		StringBuffer re = new StringBuffer();
		re.append("<业务实体块集合>");
        //（业务行为表）
		String yqActTable = userCode + "_YQACT";
		yqActTable = "YQACT";
		List<Map<String,Object>> yqactList = SpringUtils.getBean(PackMapper.class).selectYqact(yqActTable,type, (Long) da.get("ID"));
		for(Map<String,Object> yqact : yqactList) {
			re.append("<业务实体块>");
			//行为  历史行为/计划行为
			//re.append("<M80");
			re.append("<业务行为>").append(LOG_TYPE.getKey(yqact.get("ACT_TYPE").toString())).append("</业务行为>");
			re.append("<行为时间>").append(yqact.get("ACT_TIME")).append("</行为时间>");
			re.append("<机构人员名称>").append(yqact.get("USER_NAME")).append("</机构人员名称>");
			//部门信息
			//re.append("<M78>").append(yqact.get("DEPT_NAME")).append("</M78>");
			re.append("</业务实体块>");
		}
		re.append("</业务实体块集合>");
		return re.toString();
	}

	/**
	 * 获取电子属性Xml
	 * 不跟基础数据放一块,独立出来,防止后续变更
	 * @param mDataList 元数据明细
	 * @param groupId 门类ID
	 * @param da 档案
	 * @return
	 * @throws SQLException
	 */
	public FilePackage getFileXml(List<Map<String,Object>> mDataList, Long groupId, Map<String,Object> da) throws SQLException {
		FilePackage filePackage = new FilePackage();
		StringBuffer re = new StringBuffer();

		List<String> filePaths = new ArrayList<String>();
		/*re.append("<组件集合>");
		List<Map<String,Object>> docRs = DbTool.getListResult("SELECT DOC.* FROM HDDADOCUMENT DOC,HDDACATEGORY HDC WHERE HDC.ID = "+groupId+" AND DOC.DOC_TYPE = HDC.CODE AND DOC.CON_TABLE_NAME = HDC.FILETABLENAME AND CON_TABLE_ID="+da.get("ID")+" ORDER BY DOC_ORDER");
		for(Map<String,Object> docs : docRs) {
			re.append("<组件>");
//			for(Map<String,Object> mds : mDataList) {
//				String FIELDNAME = mds.get("FIELD_NAME").toString();
//				if(docs.containsKey(FIELDNAME)) {
//					String value = docs.get(FIELDNAME).toString();
//					if(StringUtils.isNULL(value)) {
//						value = "";
//					}
//					String bianhao = mds.get("BIANHAO").toString();
//					re.append("<").append(bianhao).append(">")
//					.append(value).append("</").append(bianhao).append(">");
//				}
//			}
			//TODO 暂时写死
			re.append("<格式信息>").append(docs.get("DOC_FILE_TYPE")).append("</格式信息>");
			re.append("<计算机文件名>").append(docs.get("DOC_NAME")).append("</计算机文件名>");
			re.append("<计算机文件大小>").append(docs.get("DOC_FILE_SIZE")).append("</计算机文件大小>");
			//来源
			//re.append("<文档创建程序>").append(docs.get("DOC_FILE_TYPE")).append("</文档创建程序>");
			re.append("<文件名称>").append(docs.get("REAL_DOC_NAME")).append("</文件名称>");
			//类型
			//re.append("<文件类型");
			re.append("</组件>");

			filePaths.add(docs.get("PATH").toString());
		}
		re.append("</组件集合>");*/
		filePackage.setFileXml(re.toString());
		filePackage.setFiles(filePaths);
		return filePackage;
	}
	private String packXml(Long id,Integer type,Long typeId,int cengji){
		String xml = "";
		try {
			//1.查询分表表名
//			Map<String,Object> data = null;
//			if (type == 3){
//				data =  SpringUtils.getBean(TenantYqItemMapper.class).getItemAllById("SUB_TABLE_NAME",id,new TenantYqItem().getTableName());
//			}else if(type == 1){
//				data =  SpringUtils.getBean(TenantYqFolderMapper.class).getYqFolderAllById("SUB_TABLE_NAME",id,new TenantYqdaFolder().getTableName());
//			}else if(type == 0){
//				data =  SpringUtils.getBean(TenantYqdaMapper.class).getYqdaAllById("SUB_TABLE_NAME",id,new TenantYqda().getTableName());
//			}
			//2.根据分表查询门类
			TenantCategory category =  SpringUtils.getBean(TenantCategoryMapper.class).selectTenantCategoryByID(typeId,new TenantCategory().getTableName());
			//3.查询元数据方案
			TenantMdataList selectMList = new TenantMdataList();
//			selectMList.setIsMetadata(1); //是元数据项的
			selectMList.setGroupId(category.getGroupId());
			List<TenantMdataList> mdataLists =  SpringUtils.getBean(TenantMdataListMapper.class).selectTenantMdataListList(selectMList);

			if((category.getType() == 3 || category.getType() == 1)&&cengji == 1){
				List<String> folderIds = new ArrayList<>();
//				if (category.getType() == 3){
//					//获取项目下的卷
//					folderIds =  SpringUtils.getBean(TenantItemFolderMapper.class).selectFolderIdByItemId(String.valueOf(id),new TenantItemFolder().getTableName());
//
//				}else {
//					folderIds.add(id.toString());
//				}
				folderIds.add(id.toString());

				for(String folderId:folderIds){
					//构建xml
					Document document = DocumentHelper.createDocument();
					Element dast = createTitleXml(document,category.getType());

					//查询卷信息
					Map<String,Object> juanMap =  SpringUtils.getBean(TenantYqFolderMapper.class).getYqFolderById(getColumn(mdataLists,1),Long.valueOf(folderId),category.getFolderTableName());
					if(juanMap!= null && (juanMap.get("DH") == null || "".equals(juanMap.get("DH").toString()))){
						throw new ServiceException("卷层档号没有值,打包失败！");
					}
					//档号值
					dast.addElement("电子档案号").addText(String.valueOf(juanMap.get("DH")));

					//创建档号节点
					createDhXml(dast,juanMap.get("RQ"),category,"v",folderId);

					Element daXml = dast.addElement("内容描述");

					if(juanMap!= null &&"0".equals(String.valueOf(juanMap.get("IS_DEL")))){
						//创建卷
						for(TenantMdataList mdata:mdataLists){
							if(mdata.getType() == 1){
								Element e = daXml.addElement(mdata.getFieldCaption());
								e.addText(getNull(juanMap.get(mdata.getFieldName())));
							}
						}
						//创建项目层
//						if(category.getType() == 3){
//							Map<String,Object> xmMap = SpringUtils.getBean(TenantYqFolderMapper.class).getYqFolderById(getColumn(mdataLists,3),id,category.getItemTableName());
//							Element xm = daXml.addElement("项目层");
//							for(TenantMdataList mdata:mdataLists){
//								if(mdata.getType() == 3){
//									Element e = xm.addElement(mdata.getFieldCaption());
//									e.addText(getNull(xmMap.get(mdata.getFieldName())));
//								}
//							}
//						}
						//创建件层
						List<String> daIds = SpringUtils.getBean(TenantYqdaFolderMapper.class).selectFileIdByFolderId(folderId,new TenantYqdaFolder().getTableName());
						Element jianList = daXml.addElement("件层集");
						for(String daId:daIds) {
							Map<String,Object> jianMap = SpringUtils.getBean(TenantYqdaMapper.class).getYqdaById(getColumn(mdataLists,0),Long.valueOf(daId),category.getFileTableName());
							if("0".equals(String.valueOf(juanMap.get("IS_DEL")))) {
								Element jian = jianList.addElement("件层");
								for(TenantMdataList mdata:mdataLists){
									if(mdata.getType() == 0){
										Element e = jian.addElement(mdata.getFieldCaption());
										e.addText(getNull(jianMap.get(mdata.getFieldName())));
									}
								}
//								//测试
//								jianMap.put("DH","000000");
								if(jianMap!= null && (jianMap.get("DH") == null || "".equals(jianMap.get("DH").toString()))){
									throw new ServiceException("件层档号没有值,打包失败！");
								}
								//创建电子文件节点
								createDocXml(mdataLists,daId,category,jian,juanMap.get("DH").toString(),jianMap.get("DH").toString(),"path");
							}
						}
					}
					//固定节点
					dast.addElement("形式特征").addElement("文件组合类型").addText("单件");
					dast.addElement("存储位置").addElement("脱机载体编号").addText("");
					dast.addElement("权限管理").addText("");
					//写入文件
//					writer(path+File.separator+juanMap.get("DH")+File.separator,document);
					xml = documentToString(document);
				}
			}else if(category.getType() == 0||cengji == 0){
				//构建xml
				Document document = DocumentHelper.createDocument();
				Element dast = createTitleXml(document,category.getType());
				Map<String,Object> jianMap = SpringUtils.getBean(TenantYqdaMapper.class).getYqdaById(getColumn(mdataLists,0),id,category.getFileTableName());

//				//测试
//				jianMap.put("DH","000000");

				if(jianMap!= null && (jianMap.get("DH") == null || "".equals(jianMap.get("DH").toString()))){
					throw new ServiceException("件层档号没有值,打包失败！");
				}
				dast.addElement("电子档案号").addText(String.valueOf(jianMap.get("DH")));
				//创建档号节点
				createDhXml(dast,jianMap.get("RQ"),category,"f",String.valueOf(id));

				Element daXml = dast.addElement("内容描述");
				if("0".equals(String.valueOf(jianMap.get("IS_DEL")))) {
					for(TenantMdataList mdata:mdataLists){
						if(mdata.getType() == 0){
							Element e = daXml.addElement(mdata.getFieldCaption());
							e.addText(getNull(jianMap.get(mdata.getFieldName())));
						}
					}
					//创建电子文件节点
					createDocXml(mdataLists,String.valueOf(id),category,daXml,null,jianMap.get("DH").toString(),"path");
				}
				//固定节点
				dast.addElement("形式特征").addElement("文件组合类型").addText("单件");
				dast.addElement("存储位置").addElement("脱机载体编号").addText("");
				dast.addElement("权限管理").addText("");
				//写入文件
//				writer(path+File.separator+jianMap.get("DH")+File.separator,document);
				xml = documentToString(document);
			}

		}catch (ServiceException e){
			logger.error(e.getMessage(),e);
			throw e;
		} catch (Exception e){
			logger.error(e.getMessage(),e);
			throw new ServiceException("打包失败:"+e.getMessage());
		}
		return xml;
	}

	public String documentToString(org.dom4j.Document document) {
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			StringWriter writer = new StringWriter();
			XMLWriter xmlWriter = new XMLWriter(writer, format);
			xmlWriter.write(document);
			return writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 创建部分固定节点
	 * @param document
	 * @param type
	 * @return
	 */
	private Element createTitleXml(org.dom4j.Document document, Integer type){
		Element root = document.addElement("电子档案封装包");
		root.addElement("封装包格式描述").addText("本EEP根据中华人民共和国档案行业标准DA/T 48-2009《基于XML的电子文件封装规范》生成");
		root.addElement("版本").addText("2009");
		Element dx = root.addElement("被签名对象");
		dx.addElement("封装包类型").addText("原始型");
		dx.addElement("封装包类型描述").addText("本封装包包含电子档案数据及其元数据，原始封装，未经修改");
		dx.addElement("封装包创建时间").addText(DateUtils.getTime());
		String depeName = SecurityUtils.getLoginUser().getUser().getDept().getParentName();
		dx.addElement("封装包创建单位").addText(cn.yuanqiao.common.utils.StringUtils.isNotEmpty(depeName) ? depeName:"");
		Element info = dx.addElement("封装内容");
		Element dast = info.addElement("档案实体块");
		dast.addElement("聚合层次").addText(type == 0 ? "文件":"组卷");
		dast.addElement("来源").addElement("立档单位名称").addText("");
		return dast;
	}

	/**
	 * 获取查询列
	 * @param mdataLists
	 * @param type
	 * @return
	 */
	private String getColumn(List<TenantMdataList> mdataLists, Integer type){
		StringBuilder column = new StringBuilder();
		for(TenantMdataList mdata:mdataLists){
			if(mdata.getType() == type){
				column.append(mdata.getFieldName()).append(",");
			}
		}
		if(column.length()>0){
			column.append("IS_DEL");
			if(type == 0 || type==1){
				column.append(",RQ,DH");
			}else if(type == 2){
				column.append(",TYPE,REAL_DOC_NAME,PATH");
			}
		}else {
			throw new ServiceException(type == 3 ? "项目层":(type == 1 ? "卷层":(type == 0 ? "件层":(type == 2 ? "电子文件层":""))) +"没有勾选元数据项");
		}
		return column.toString();
	}

	/**
	 * 创建档号节点
	 * @param dast
	 * @param RQ
	 * @param category
	 * @param type
	 * @param daId
	 */
	private void createDhXml(Element dast, Object RQ, TenantCategory category, String type, String daId){
		//档号组成
		List<Map<String,String>> rule = null;
		if(RQ!=null && cn.yuanqiao.common.utils.StringUtils.isNotEmpty(String.valueOf(RQ))){
			//根据日期获取档号规则
			rule = SpringUtils.getBean(TenantCodeListMapper.class).getCodeListByCategoryId(category.getId(),new TenantCodeList().getTableName(),new TenantCodeRule().getTableName(),
					Integer.valueOf(String.valueOf(RQ)),"著录项值",type);
		}
		if(rule == null || rule.size()==0){
			//使用默认档号规则
			rule = SpringUtils.getBean(TenantCodeListMapper.class).getCodeListByCategoryId(category.getId(),new TenantCodeList().getTableName(),new TenantCodeRule().getTableName(),null,"著录项值",type);
		}
		if(rule != null || rule.size()!=0){
			Element dhXml = dast.addElement("档号");
			StringBuilder selectSql = new StringBuilder();
			List<String> selectCol = new ArrayList<>();
			for(int i = 0;i<rule.size();i++){
				selectSql.append(rule.get(i).get("NODE_VALUE")+",");
				selectCol.add(rule.get(i).get("NODE_VALUE"));
			}
			if(selectSql.length()>0){
				selectSql.append("IS_DEL");
				TenantMdataList select = new TenantMdataList();
				select.setGroupId(category.getGroupId());
				select.setType("f".equals(type) ? 0:1);
				//查询组成档号字段的元数据明细
				List<TenantMdataList> mdataLists = SpringUtils.getBean(TenantMdataListMapper.class).selectByFieldName(selectCol,select);
				if("v".equals(type)){
					//查询组成档号字段的值
					Map<String,Object> juanDhMap = SpringUtils.getBean(TenantYqFolderMapper.class).getYqFolderById(selectSql.toString(),Long.valueOf(daId),category.getFolderTableName());
					for(Map<String,String> dhCol:rule){
						for(TenantMdataList mdata:mdataLists){
							if(mdata.getType() == 1 && dhCol.get("NODE_VALUE").equals(mdata.getFieldName())){
								//档号节点内容
								dhXml.addElement(mdata.getFieldCaption()).addText(getNull(juanDhMap.get(dhCol.get("NODE_VALUE"))));
							}
						}
					}
				}else if("f".equals(type)){
					Map<String,Object> jianDhMap = SpringUtils.getBean(TenantYqdaMapper.class).getYqdaById(selectSql.toString(),Long.valueOf(daId),category.getFileTableName());
					for(Map<String,String> dhCol:rule){
						for(TenantMdataList mdata:mdataLists){
							if(mdata.getType() == 0 && dhCol.get("NODE_VALUE").equals(mdata.getFieldName())){
								//档号节点内容
								dhXml.addElement(mdata.getFieldCaption()).addText(getNull(jianDhMap.get(dhCol.get("NODE_VALUE"))));
							}
						}
					}
				}

			}
		}else {
			throw new ServiceException("没有配置档号规则!");
		}
	}

	/**
	 * 创建电子文件节点
	 * @param mdataLists
	 * @param daId
	 * @param category
	 * @param jian
	 * @param juanDh
	 * @param jianDh
	 * @param path
	 * @throws IOException
	 */
	private void createDocXml(List<TenantMdataList> mdataLists, String daId, TenantCategory category, Element jian, String juanDh, String jianDh, String path){
		//电子文件层
		List<Map<String, Object>> docList = SpringUtils.getBean(TenantYqdaDocumentMapper.class).getDocumentBydaId(getColumn(mdataLists,2),Long.valueOf(daId),category.getEfileTableName(),"");
		Element docXmlList = jian.addElement("文件数据集");
		for(Map<String, Object> docMap:docList){
			if("0".equals(String.valueOf(docMap.get("IS_DEL")))){
				Element wd = docXmlList.addElement("文件数据").addElement("文档");
				wd.addElement("文档标识符").addText("");
				wd.addElement("文档主从声明").addText(getNull(docMap.get("TYPE")));
				Element bm = wd.addElement("文档数据").addElement("编码");
				Element dzsx = bm.addElement("电子属性");
				for(TenantMdataList docMdata:mdataLists){
					if(docMdata.getType() == 2){
						Element docXml = dzsx.addElement(docMdata.getFieldCaption());
						docXml.addText(getNull(docMap.get(docMdata.getFieldName())));
					}
				}
				bm.addElement("编码描述").addText("本封装包中“编码数据”元素存储的是计算机文件二进制流的Base64编码，有关Base64编码规则参见IETF RFC 2045多用途邮件扩展（MIME）第一部分：互联网信息体格式。当提取和显现封装在编码数据元素中的计算机文件时，应对Base64编码进行反编码，并依据封装包中“反编码关键字”元素中记录的值还原计算机文件的扩展名");
				bm.addElement("反编码关键字").addText("");
				bm.addElement("编码数据").addText("");
			}
		}
	}

	private String getNull(Object val){
		if(val == null){
			return "";
		}else {
			return String.valueOf(val);
		}
	}

}
